package com.jacen.aws;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.jacen.aws.entity.KeyEntity;
import com.jacen.aws.entity.vo.ViewVo;
import com.jacen.aws.exception.ClientException;
import com.jacen.aws.service.IpService;
import com.jacen.aws.setting.Setting;
import com.jacen.aws.util.DialogUtil;
import com.jacen.aws.util.FileUtil;
import com.jacen.aws.util.LogUtil;
import com.jacen.aws.util.StringUtil;
import com.jacen.aws.util.WindowUtil;

/**
 * 版权声明：Copyright(c) 2018 All Rights Reserved.
 *
 * @Author Jacen (295117485@qq.com)
 * @Date 2018/10/13 8:39
 * @Version 1.0
 * @Description 主界面
 */
public class MainView extends JFrame implements ActionListener, ItemListener, MouseListener {

	private JPanel panel;
	private JLabel lbInstanceId, lbBlackIp;

	private JButton btnReadIp;
	private JButton btnChangeIp;
	private JButton btnCopy;
	private JButton btnSave;
	private JButton btnBlack;

	private ButtonGroup btnRadioGroup;
	private JTextField txtPublicIp;
	private JTextArea txtAreaLog;
	private JScrollPane jsp;
	private JList<String> ipList, blackIpList;

	private String currentRegion = "";
	private static boolean isAction = false;

	public MainView() {
		init();
		setResizable(false);
		setTitle(Setting.TITLE_NAME);
		setBounds(200, 200, 520, 480);
		setVisible(true);
		JFrame.setDefaultLookAndFeelDecorated(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	private void init() {
		panel = new JPanel();
		panel.setLayout(null);

		lbInstanceId = new JLabel(Setting.LABEL_INSTANCE_ID, JLabel.CENTER);
		lbInstanceId.setBounds(10, 20, 50, 30);
		panel.add(lbInstanceId);

		btnReadIp = new JButton(Setting.BTN_READ);
		btnReadIp.setBounds(420, 20, 80, 30);
		btnReadIp.addActionListener(this);
		panel.add(btnReadIp);

		txtPublicIp = new JTextField(20);
		txtPublicIp.setBounds(10, 60, 120, 30);
		txtPublicIp.setEditable(false);
		panel.add(txtPublicIp);

		txtAreaLog = new JTextArea();
		txtAreaLog.setEditable(false);
		jsp = new JScrollPane(txtAreaLog);
		jsp.setBounds(140, 100, 360, 340);
		jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		panel.add(jsp);

		initList();
		initRadioBtn();
		initBtn();

		add(panel);
		initIp();
	}

	private void initIp() {
		Vector<String> ips = readIpWhiteList(currentRegion);
		if (ips != null) {
			ipList.setListData(ips);
			LogUtil.printMessage(txtAreaLog, "读取ip文件成功:" + currentRegion);
		}

		Vector<String> blackList = readIpBlackList();
		if (blackList != null) {
			blackIpList.setListData(blackList);
			LogUtil.printMessage(txtAreaLog, "读取ip黑名单文件成功");
		}
	}

	private void initRadioBtn() {
		btnRadioGroup = new ButtonGroup();
		JRadioButton btnRadio = null;
		int i = 0;
		for (String region : Setting.keyMap.keySet()) {
			btnRadio = new JRadioButton(Setting.keyMap.get(region).getNickName() + "(" + region + ")",
					(i == 0) ? true : false);
			btnRadio.setBounds(70 + (i * 120), 20, 120, 30);
			btnRadio.setActionCommand(region);
			btnRadio.addItemListener(this);
			btnRadioGroup.add(btnRadio);
			panel.add(btnRadio);
			if (i == 0) {
				currentRegion = region;
			}
			i++;
		}
	}

	private void initBtn() {
		btnSave = new JButton(Setting.BTN_WHITE);
		btnSave.setBounds(140, 60, 65, 30);
		btnSave.addActionListener(this);
		btnSave.setEnabled(false);
		panel.add(btnSave);

		btnBlack = new JButton(Setting.BTN_BLACK);
		btnBlack.setBounds(210, 60, 65, 30);
		btnBlack.addActionListener(this);
		btnBlack.setEnabled(false);
		panel.add(btnBlack);

		btnCopy = new JButton(Setting.BTN_COPY);
		btnCopy.setBounds(280, 60, 65, 30);
		btnCopy.addActionListener(this);
		btnCopy.setEnabled(false);
		panel.add(btnCopy);

		btnChangeIp = new JButton(Setting.BTN_CHANGE);
		btnChangeIp.setBounds(420, 60, 80, 30);
		btnChangeIp.addActionListener(this);
		btnChangeIp.setEnabled(false);
		panel.add(btnChangeIp);
	}

	private void initList() {
		ipList = new JList<>();
		ipList.setName(Setting.LIST_IP_NAME);
		ipList.addMouseListener(this);

		JScrollPane scrollPane1 = new JScrollPane(ipList);
		scrollPane1.setBounds(10, 100, 120, 160);
		panel.add(scrollPane1);

		lbBlackIp = new JLabel(Setting.LABEL_BLACK_IP, JLabel.LEFT);
		lbBlackIp.setBounds(10, 270, 50, 30);
		panel.add(lbBlackIp);

		blackIpList = new JList<>();
		blackIpList.setName(Setting.LIST_BLACK_IP_NAME);
		blackIpList.addMouseListener(this);

		JScrollPane scrollPane2 = new JScrollPane(blackIpList);
		scrollPane2.setBounds(10, 300, 120, 140);
		panel.add(scrollPane2);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		String action = event.getActionCommand();
		currentRegion = btnRadioGroup.getSelection().getActionCommand();
		ViewVo view = getView(currentRegion);
		if (view == null) {
			DialogUtil.showErrorDialog(panel, "哥，系统出错了:" + currentRegion);
			return;
		}

		try {
			if (Setting.BTN_READ.equalsIgnoreCase(action)) {
				LogUtil.printMessage(view.getTextArea(), "读取开始:" + currentRegion);
				IpService.read(view);
				btnEnable();
				LogUtil.printMessage(view.getTextArea(), "读取结束:" + currentRegion);
			} else if (Setting.BTN_CHANGE.equalsIgnoreCase(action)) {
				LogUtil.printMessage(view.getTextArea(), "切换开始:" + currentRegion);
				IpService.change(view);
				LogUtil.printMessage(view.getTextArea(), "切换结束:" + currentRegion);
			} else if (Setting.BTN_COPY.equalsIgnoreCase(action)) {
				String publicIp = txtPublicIp.getText().trim();
				WindowUtil.setSysClipboardText(publicIp);
				LogUtil.printMessage(view.getTextArea(), "复制成功:" + publicIp);
			} else if (Setting.BTN_WHITE.equalsIgnoreCase(action)) {
				String publicIp = txtPublicIp.getText().trim();
				if (StringUtil.isEmpty(publicIp)) {
					DialogUtil.showErrorDialog(panel, "ip不能为空");
					return;
				}
				boolean success = Setting.ipSet.add(publicIp);
				if (!success) {
					DialogUtil.showErrorDialog(panel, "ip已存在白名单中:" + currentRegion + ":" + publicIp);
					return;
				}
				Vector<String> vector = new Vector<>();
				for (String ip : Setting.ipSet) {
					vector.add(ip);
				}
				Vector<String> list = readIpWhiteList(currentRegion);
				if (list == null) {
					list = new Vector<>();
				}
				list.add(publicIp);
				ipList.setListData(list);
				try {
					String fileName = String.format(Setting.SETTING_REGION_IP_FILE_PATH, currentRegion);
					IpService.saveToIpList(fileName, publicIp);
					LogUtil.printMessage(view.getTextArea(), "写入文件成功:" + currentRegion + ":" + publicIp);
				} catch (Exception e) {
					DialogUtil.showErrorDialog(panel, "ip写入文件异常" + currentRegion + ":" + publicIp);
				}
			} else if (Setting.BTN_BLACK.equalsIgnoreCase(action)) {
				String publicIp = txtPublicIp.getText().trim();
				if (StringUtil.isEmpty(publicIp)) {
					DialogUtil.showErrorDialog(panel, "ip不能为空");
					return;
				}
				String p = publicIp.substring(0, StringUtil.getCharIndexTimes(publicIp, ".", 2) + 1);
				String content = FileUtil.readTxtFile(Setting.SETTING_BLACK_IP_FILE_PATH);
				if (content.indexOf(p) > -1) {
					DialogUtil.showErrorDialog(panel, "ip已存在黑名单中");
					return;
				}
				IpService.saveToIpList(Setting.SETTING_BLACK_IP_FILE_PATH, p);
				Vector<String> blackList = readIpBlackList();
				blackIpList.setListData(blackList);
			} else {
				DialogUtil.showErrorDialog(panel, "哥，还有这种操作？？？:" + action);
			}
		} catch (Exception e) {
			isAction = false;
			LogUtil.printMessage(view.getTextArea(), "系统错误：" + e.getMessage());
			e.printStackTrace();
			DialogUtil.showErrorDialog(panel, "哥，出错了:" + e.getMessage());
		}
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		JRadioButton button = (JRadioButton) e.getSource();
		if (!button.isSelected()) {
			return;
		}
		String radioAction = button.getActionCommand();
		currentRegion = radioAction;
		ViewVo view = getView(radioAction);
		if (view == null) {
			DialogUtil.showErrorDialog(panel, "哥，系统出错了:" + radioAction);
			return;
		}
		LogUtil.printMessage(view.getTextArea(), "读取开始:" + radioAction);
		isAction = true;
		IpService.read(view);
		Vector<String> ips = readIpWhiteList(currentRegion);
		if (ips != null) {
			ipList.setListData(ips);
			LogUtil.printMessage(txtAreaLog, "读取ip文件成功:" + radioAction);
		} else {
			ipList.setListData(new Vector<>());
		}
		btnEnable();
		isAction = false;
		LogUtil.printMessage(view.getTextArea(), "读取结束:" + radioAction);
	}

	private ViewVo getView(String radioAction) {
		ViewVo view = new ViewVo();
		view.setPanel(panel);
		view.setTextArea(txtAreaLog);
		view.setTxtPublicIp(txtPublicIp);

		KeyEntity keyEntity = Setting.keyMap.get(radioAction);
		if (keyEntity == null) {
			return null;
		}
		view.setKeyEntity(keyEntity);

		Vector<String> ips = readIpWhiteList(radioAction);
		view.setIpWhiteList(ips);
		Vector<String> blackList = readIpBlackList();
		view.setIpBlackList(blackList);
		return view;
	}

	public Vector<String> readIpWhiteList(String region) {
		try {
			String fileName = String.format(Setting.SETTING_REGION_IP_FILE_PATH, region);
			Vector<String> ips = IpService.readIpList(fileName);
			return ips;
		} catch (Exception e) {
			LogUtil.printMessage(txtAreaLog, "读取ip文件失败:" + e.getMessage());
			return null;
		}
	}

	public Vector<String> readIpBlackList() {
		try {
			Vector<String> ips = IpService.readIpList(Setting.SETTING_BLACK_IP_FILE_PATH);
			return ips;
		} catch (Exception e) {
			LogUtil.printMessage(txtAreaLog, "读取ip黑名单文件失败:" + e.getMessage());
			return null;
		}
	}

	@Override
	public void mouseClicked(MouseEvent e) {

		JList list = (JList) e.getSource();
		String name = list.getName();

		if (list.getSelectedValue() == null) {
			return;
		}

		int clickCount = e.getClickCount();
		String selectValue = list.getSelectedValue().toString();
		Vector<String> ipList = null;
		if (Setting.LIST_IP_NAME.equalsIgnoreCase(name)) {
			if (clickCount == Setting.DOUBLE_CLICK) {
				LogUtil.printMessage(txtAreaLog, "选中: " + selectValue + "进行替换...");
				// TODO: 2018/10/18 切换ip
				FileUtil.deleteFileContent(String.format(Setting.SETTING_REGION_IP_FILE_PATH, currentRegion),
						selectValue);
				try {
					IpService.associateAddress(getView(currentRegion), selectValue);
				} catch (ClientException e1) {
					LogUtil.printMessage(txtAreaLog, "替换异常：" + e1.getMessage());
				}
				ipList = readIpWhiteList(currentRegion);

				Setting.ipSet.remove(selectValue);
				btnEnable();
			}
		} else {
			if (clickCount == Setting.DOUBLE_CLICK) {
				// TODO: 2018/10/18 删除文件中的ip
				FileUtil.deleteFileContent(Setting.SETTING_BLACK_IP_FILE_PATH, selectValue);
				ipList = readIpBlackList();
				LogUtil.printMessage(txtAreaLog, "删除: " + selectValue + "黑名单");

				Setting.blackIpSet.remove(selectValue);
			}
		}

		if (clickCount == Setting.DOUBLE_CLICK) {
			if (ipList != null) {
				ipList.remove(selectValue);
				list.setListData(ipList);
			} else {
				ipList = new Vector<>();
				list.setListData(ipList);
			}

		}
	}

	private void btnEnable() {
		btnSave.setEnabled(true);
		btnBlack.setEnabled(true);
		btnCopy.setEnabled(true);
		btnChangeIp.setEnabled(true);
	}

	@Override
	public void mousePressed(MouseEvent e) {

	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	}

	@Override
	public void mouseExited(MouseEvent e) {
	}

	public static void main(String[] args) {
		new MainView();
	}
}